package com.diyunapp.xilinapp.me;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.bean.AddressBean;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.selfdefine.StatusBarFragmentActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddressActivity extends StatusBarFragmentActivity {

    @Bind(R.id.add_address_tv)
    TextView addAddressTv;
    @Bind(R.id.go_back)
    ImageView goBack;
    @Bind(R.id.integral_fresh_lv)
    ListView integralFreshLv;
    @Bind(R.id.integral_refresh_view)
    SwipeRefreshLayout integralRefreshView;
    private List<AddressBean.DatasBean.AddressListBean> info=new ArrayList<>();
    private LayoutInflater inflater;
    private AddressAdapter addressAdapter;
    private String key;
    private String member_id;
    private View headView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        addressAdapter=new AddressAdapter(this);
        ButterKnife.bind(this);
        headView = findViewById(R.id.address_menubar_inc);
        super.MenuWidget(headView);
        initView();
        initAddress();
        integralFreshLv.setAdapter(addressAdapter);
    }

    private void initView() {
        integralRefreshView.setColorSchemeColors(R.color.domain_orange, R.color.green,
                R.color.blue, R.color.yellow);

        integralRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("zhangxiaoxidebug", "myordersSwiperefreshlayout onRefresh...");
                initAddress();
            }
        });

        integralRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("onRefresh", "invoke onRefresh...");
                if(MainActivity.myLogin.isLoginState())
                {
                    initAddress();
                }
                else
                {
                    toast("您还没有登录！");
                    integralRefreshView.setRefreshing(false);
                }
            }
        });
    }

    @OnClick({R.id.add_address_tv, R.id.go_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_address_tv:
                Intent setInt = new Intent(this, AddAddressActivity.class);
                startActivityForResult(setInt, 1);
                break;
            case R.id.go_back:
                finish();
                break;


        }
    }
    private void initAddress() {
        String url = ""+MainActivity.url+"act=member_address&op=address_list&key="+ MainActivity.myLogin.getLoginkey()+"";
//        String url = "http://xilin.diyunkeji.com/mobile/index.php?act=member_address&op=address_list&key="+key+"";
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(10000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {}
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        bidFreshLv.onRefreshComplete();
                        integralRefreshView.setRefreshing(false);
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        Logger.e("=================================="+resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
                            if (result == 200) {
                                JSONObject information = resultObject.optJSONObject("datas");
                                info.clear();
                                JSONArray listArray=information.optJSONArray("address_list");
                                for (int i = 0; i < listArray.length(); i++) {
                                    JSONObject recordObject = listArray.optJSONObject(i);
                                    String address = recordObject.optString("address");
                                    String address_id = recordObject.optString("address_id");
                                    String area_id = recordObject.optString("area_id");
                                    String area_info = recordObject.optString("area_info");
                                    String city_id = recordObject.optString("city_id");
                                    String dlyp_id = recordObject.optString("dlyp_id");
                                    int is_default = recordObject.optInt("is_default");
                                    String member_id = recordObject.optString("member_id");
                                    String mob_phone = recordObject.optString("mob_phone");
                                    String tel_phone=recordObject.optString("tel_phone");
                                    String true_name=recordObject.optString("true_name");


                                    info.add(new AddressBean.DatasBean.AddressListBean(address, address_id, area_id,area_info,
                                            city_id,dlyp_id,is_default,member_id,mob_phone,tel_phone,true_name));
                                }
                                addressAdapter.setList(info);
                                addressAdapter.notifyDataSetChanged();

                            } else {
                                toast("当前暂无数据");
                                integralRefreshView.setVisibility(View.GONE);

                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();
                            integralRefreshView.setVisibility(View.GONE);
                        }
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
                        integralRefreshView.setRefreshing(false);
                        toast("请求失败");
                        integralRefreshView.setVisibility(View.GONE);
                    }
                });
    }

    class AddressAdapter extends BaseAdapter {
        private List<AddressBean.DatasBean.AddressListBean> info = new ArrayList<AddressBean.DatasBean.AddressListBean>();
        private Context context;
        public AddressAdapter(Context context) {
            super();
            this.context = context;
        }

        public void setList(List<AddressBean.DatasBean.AddressListBean> list) {
            this.info = list;
            notifyDataSetChanged();
        }
        @Override
        public int getCount() {
            return null == info ? 0 : info.size();
        }

        @Override
        public Object getItem(int position) {
            return null == info ? null : info.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
        public  ViewHolder viewHolder;
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {


            if (null == convertView) {

                convertView = inflater.inflate(R.layout.item_address, null);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.editTv.setTag(position);
            viewHolder.deleteTv.setTag(position);
            viewHolder.checkMoren.setTag(position);
            final AddressBean.DatasBean.AddressListBean data_info=info.get(position);
            viewHolder.nameTv.setText(data_info.getTrue_name());
            viewHolder.phoneTv.setText(data_info.getMob_phone());
            viewHolder.addressTv.setText(data_info.getArea_info()+data_info.getAddress());
            int is_default=data_info.getIs_default();
            if (is_default==1){
                viewHolder.checkMoren.setImageResource(R.drawable.xuan);

            }else {
                viewHolder.checkMoren.setImageResource(R.drawable.wei);

            }
            final String area_info=data_info.getArea_info();
            final String address=data_info.getAddress();
            final int a=info.get(position).getIs_default();
            viewHolder.lin_moren.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(a==1){

                    }else {
                        String id = data_info.getAddress_id();
                        initMoren(id);
                        info.clear();

                    }

                }
            });
//            viewHolder.editTv.setOnClickListener(new on);
             final String addressId=data_info.getAddress_id();

            viewHolder.editTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(AddressActivity.this, EditAddressActivity.class);
                    intent.putExtra("addressId",data_info.getAddress_id());
                    intent.putExtra("name", viewHolder.nameTv.getText().toString());
                    intent.putExtra("phone",viewHolder.phoneTv.getText().toString());
                    intent.putExtra("area_info",area_info);
                    intent.putExtra("address",address);
                    startActivity(intent);
                }
            });
            viewHolder.deleteTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    initDelete(addressId);
                    info.clear();
                    initAddress();

                }
            });
            return convertView;

        }


         class ViewHolder {
            @Bind(R.id.name_tv)
            TextView nameTv;
            @Bind(R.id.phone_tv)
            TextView phoneTv;
            @Bind(R.id.address_tv)
            TextView addressTv;
            @Bind(R.id.check_moren)
            ImageView checkMoren;
            @Bind(R.id.sheweimoren)
            TextView sheweimoren;
             @Bind(R.id.lin_moren)
             RelativeLayout lin_moren;
            @Bind(R.id.edit_address)
            ImageView editAddress;
            @Bind(R.id.edit_tv)
            TextView editTv;
            @Bind(R.id.delete_address)
            ImageView deleteAddress;
            @Bind(R.id.delete_tv)
            TextView deleteTv;
             @Bind(R.id.shewei)
             TextView shewei;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }

    private void initMoren(String id) {
        String url = ""+MainActivity.url+"act=goods&op=default_addrss" +
                "&member_id="+MainActivity.myLogin.getMemberid()+"&id="+id+"&is_default=1";
//        String url = "http://xilin.diyunkeji.com/mobile/index.php?act=goods&op=default_addrss&member_id="+member_id+"&id="+id+"&is_default=1";

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {}
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        bidFreshLv.onRefreshComplete();
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        Logger.e("=================================="+resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
                            if (result == 200) {
                                String state=resultObject.optString("data");
                                     initAddress();

                                    toast("修改成功");

                            }
                            else{
                                String state=resultObject.optString("data");
                                toast(state);
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();

                        }
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {

                        toast("请求失败");

                    }
                });
    }

    private void initDelete(String id) {
            String url = ""+MainActivity.url+"act=member_address" +
                    "&op=address_del&key="+MainActivity.myLogin.getLoginkey()+"&address_id="+id+"";
//        String url = "http://xilin.diyunkeji.com/mobile/index.php?act=member_address&op=address_del&key="+key+"&address_id="+id+"";
            HttpUtils http = new HttpUtils();
            http.configCurrentHttpCacheExpiry(1000);
            http.send(HttpRequest.HttpMethod.POST, url,
                    new RequestCallBack<String>() {
                        @Override
                        public void onLoading(long total, long current, boolean isUploading) {}
                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
//                        bidFreshLv.onRefreshComplete();
                            String resultinfo = responseInfo.result;
                            Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        Logger.e("=================================="+resultinfo);
                            try {
                                JSONObject resultObject = new JSONObject(resultinfo);
                                int result = resultObject.optInt("code");
//                                toast(String.valueOf(result));
                                if (result == 200) {
                                    JSONObject information = resultObject.optJSONObject("datas");
                                    String state=resultObject.optString("datas");
                                    if (state.equals("1")){
                                        toast("删除成功");
                                    }else{
                                        String error=information.optString("error");
                                        toast(error);
                                    }
                                }
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                toast("查询失败");
                                e.printStackTrace();

                            }
                        }
                        @Override
                        public void onFailure(HttpException error, String msg) {

                            toast("请求失败");

                        }
                    });
        }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (resultCode == 1) {
                initAddress();

            }
        }
    }
    public void nextAct(Class act) {
        Intent intent = new Intent();
        intent.setClass(this, act);
        startActivity(intent);
    }

}
